package domain;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.json.JSONException;
import org.json.JSONObject;

public class User implements WritableComparable<User>{
	
	private String lang;
	private String screen_name;
	private static User instance;

	//singleton User instance
	static synchronized public User getInstance(){
		if(instance == null){
			return new User();
		}else{
			return instance;
		}
	}	   
	
	public String getLang() {
		return lang;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public String getScreen_name() {
		return screen_name;
	}

	public void setScreen_name(String screenName) {
		screen_name = screenName;
	}

	@Override
	public void readFields(DataInput arg0) throws IOException {
//		try {
			parseUserFromString(arg0.toString());
//		} catch (JSONException e) {
//			System.out.print(e.getMessage() + e.getCause());
//		}
		
	}

	@Override
	public void write(DataOutput arg0) throws IOException {
		arg0.writeUTF(User.getInstance().toString());
		
	}
	
	@Override
	public String toString(){
		return User.getInstance().getScreen_name()  + " - " + User.getInstance().getLang();
	}
	
	public static User parseUserFromString(String data) {
		User user = User.getInstance();
		JSONObject myjSON;
		try {
			myjSON = new JSONObject(data);
			if(myjSON.has("user")){
				user.setLang(myjSON.getJSONObject("user").getString("lang"));
			}else{
				//throw new JSONException("user language not available");
				user.setLang("unknown");
			}	
			if(!myjSON.has("entities") || myjSON.getJSONObject("entities").getJSONArray("user_mentions").isNull(0)){
				//throw new JSONException("user mentions not available");
				user.setScreen_name("no_screen_name");
			}else{
				user.setScreen_name(myjSON.getJSONObject("entities").getJSONArray("user_mentions").getJSONObject(0).getString("screen_name"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
		return user;
	}

	@Override
	public int compareTo(User o) {
		return this.toString().compareTo(o.toString());
	}
}